package com.example.handler;

import com.example.service.RedisAuthService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class WeChatMessageHandler implements WxMpMessageHandler {

    @Autowired
    private RedisAuthService redisAuthService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                  Map<String, Object> context,
                                  WxMpService wxMpService,
                                  WxSessionManager sessionManager) {
        // 简化版扫码处理，仅用于测试
        if ("event".equals(wxMessage.getMsgType()) && "SCAN".equals(wxMessage.getEvent())) {
            String sessionId = wxMessage.getEventKey(); // 直接使用eventKey作为sessionId
            String openId = "test_openid_" + System.currentTimeMillis(); // 模拟openId

            redisAuthService.saveLoginStatus(
                sessionId,
                openId,
                "测试用户",  // 模拟昵称
                "https://picsum.photos/200/300"  // 模拟头像
            );

            return WxMpXmlOutMessage.TEXT()
                    .content("<a href=\"http://localhost:8080/home\">点击跳转到首页</a>")
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .build();
        }
        return null;
    }
}